$(document).ready(function() {
	makeRequest(); // Activate the request sequence
});

/**
 * This is the timer that sets the intervals between requests
 */
function makeRequest() {
	var interval 	= 60000,
		url			= defineUrl();
	
	getData(url, interval);

}

/**
 * Define the url that is going to be used for the ajax request
 * 
 * @returns String: the url that is to be used
 */
function defineUrl() {
	var vars = getUrlVars(),
		bits = [];
	
	$.each(vars, function(index, value) {
		bits.push(value + '=' + vars[value].join('+'));
	});
	return bits ? "gettweets/" + '?' + bits.join('&') : "gettweets/";
}

/**
 * Make an ajax request to get new data
 * 
 * @param url: The url to be used for the request (needs to be a relative url)
 * @param interval: The interval of the timer, used for calculating the interval between appending tweets
 */
function getData(url, interval) {
	$.ajax({
		url: 			url,
		context: 		document.body,
		dataType: 		"json",
		type:			"get",
		success: 		function(data){
			if(data[0].id === -1) {
				$(".tweetstream").prepend(
						"<div class='tweet'>" +
							"<div class='tweet_account'> Lege stream </div>" +
							"<div class='tweet_message'> De stream is leeg, dit betekend dat er de afgelopen tijd geen nieuwe tweet is geplaatst die aan de zoekvoorwaarden voldoet. </div>" +
						"</div>" +
						"<div class='clear'></div>"
				);
				removeTweet();
				setTimeout("makeRequest()", interval);
			} else {
				var tweetInterval = interval/data.length
				showData(tweetInterval, data);
			}
		},
		error:			function(request, status, error) {
			$(".tweetstream").prepend(
					"<div class='tweet'>" +
						"<div class='tweet_account'>" + request.status + " " + status + "</div>" +
						"<div class='tweet_message'>" + error + "</div>" +
					"</div>" +
					"<div class='clear'></div>"
			);
		}
	});
}

/**
 * This is the function used to manage how the data is displayed
 * 
 * @param interval: the interval between the appending of tweets
 * @param tweetList: The list with tweets from the last update
 */
function showData(interval, tweetList) {
	if(tweetList.length === 0){
		makeRequest();
	} else {
		appendTweet(tweetList.shift());
		removeTweet();
		newInterval = interval;
		newTweetList = tweetList;
		setTimeout("showData(newInterval, newTweetList)", newInterval);
	}
}

/**
 * This is the function that does the actual appending of the tweet in HTML
 * 
 * @param tweet: The tweet to be appended
 */
function appendTweet(tweet) {
	$(".tweetstream").prepend(
			"<div class='tweet'>" +
				"<div class='tweet_account'>" + tweet['owner'].name + "</div>" +
				"<div class='tweet_message'>" + tweet.text + "</div>" +
			"</div>" +
			"<div class='clear'></div>"
	);
}

/**
 * This function does the actual removal of the tweet from the list
 */
function removeTweet() {
	if( $("#tweetstream").children(".tweet").size() >= 15) {
		$("#tweetstream :last").remove();
		$("#tweetstream :last").parent().remove();
	}
}